/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.proyectoTiberio.servicio;

import com.google.gson.Gson;
import com.proyectoTiberio.entity.BaseEntity;
import com.proyectoTiberio.entity.EdificioEntity;
import com.proyectoTiberio.entity.PlayerInfoEntity;
import com.proyectoTiberio.entity.PollEntity;
import com.proyectoTiberio.entity.ServerInfoEntity;
import com.proyectoTiberio.utility.GsonUtility;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.apache.http.Header;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.cookie.Cookie;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;


/**
 *
 * @author Chema
 */
public class ServicioHttp extends Servicio{

    

    public ServicioHttp() {

        httpclient = new DefaultHttpClient();

    }

    public ServerInfoEntity conectar(int i) {
        try {

            ArrayList<String> args = new ArrayList<String>();

            args.add("id");
            args.add("");
            
            //TODO: hacer bien
            if(i==1)
            {
                args.add("j_username");
            args.add("050686c@gmail.com");
            }else
            {
            
            args.add("j_username");
            args.add("josemariapfm@hotmail.com");
            
            }
            args.add("j_password");
            args.add("05junio06");
            
            args.add("spring-security-redirect");
            args.add("");
            args.add("timezone");
            args.add("0");

            if (realizarSolicitudPost(LOGIN_URL, args, true)) {
                if (realizarSolicitudGet(URL_HOME, false)) {
                    if (obtenerSession(URL_GET_SESSION, true)) {
                        args = new ArrayList<String>();
                        args.add("session");
                        args.add(idSesion);
                        args.add("refId");
                        args.add(String.valueOf(new Date().getTime()));
                        args.add("version");
                        args.add("-1");

                        obtenerSessionPpal(AJAX_ENDPOINT + "openSession", args, true);
                        String RespuestajSon = realizarSolicitudPostJSON(AJAX_ENDPOINT + "GetServerInfo", args, true);
                        ServerInfoEntity serverInfo = gson.fromJson(RespuestajSon, ServerInfoEntity.class);

                        if (serverInfo != null) {
                            return serverInfo;
                        } else {
                            System.out.println("ERROR al parsear ServerInfoEntity ");
                            return null;
                        }

                    } else {
                        return null;
                    }
                }


            } else {
                return null;
            }



        } catch (Exception e) {
            System.out.println(e);
            return null;
        }

        return null;
    }

    private boolean realizarSolicitudPost(String url, ArrayList<String> args, boolean mostrarRespuesta) throws Exception {

        HttpPost httpost = new HttpPost(url);

        //mejorar para poder enviar mas de un parametro
        if (args != null) {
            List<NameValuePair> nvps = new ArrayList<NameValuePair>();

            for (int i = 0; i < args.size(); i = i + 2) {
                nvps.add(new BasicNameValuePair(args.get(i), args.get(i + 1)));
            }


            httpost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));
        }



        HttpResponse response = httpclient.execute(httpost);


        System.out.println("Solicitud para :" + url);

        System.out.println("Cabecera :" + httpost.getAllHeaders().toString());
        for (Header a : httpost.getAllHeaders()) {
            System.out.println(a.getValue());
        }

        mostrarRespuesta(response, mostrarRespuesta);
        httpost.releaseConnection();
        return (response.getStatusLine().getStatusCode() == 200) || (response.getStatusLine().getStatusCode() == 302);

    }

    private void mostrarRespuesta(HttpResponse response, boolean mostrarCuerpo) throws Exception {

        System.out.println("Respuesta del servidor: " + response.toString());
        if (mostrarCuerpo) {

            System.out.println("cuerpo de la respuesta: ");
            InputStreamReader isr = new InputStreamReader(response.getEntity().getContent());
            BufferedReader in = new BufferedReader(isr);
            String linea = in.readLine();
            while (linea != null) {
                System.out.println(linea);
                linea = in.readLine();

            }

        }
        System.out.println("Post cookies:");
        List<org.apache.http.cookie.Cookie> cookies = httpclient.getCookieStore().getCookies();

        if (cookies.isEmpty()) {

            System.out.println("No se ha recibido ninguna cookie");

        } else {

            for (Cookie cookie : cookies) {
                System.out.println("cookie->" + cookie);
            }
        }
    }

    private boolean obtenerSession(String url, boolean b) throws Exception {

        HttpGet httpget = new HttpGet(url);
        HttpResponse response = httpclient.execute(httpget);

        boolean encontrado = false;
        InputStreamReader isr = new InputStreamReader(response.getEntity().getContent());
        BufferedReader in = new BufferedReader(isr);
        String linea;
        while ((linea = in.readLine()) != null && !encontrado) {
            if (linea.contains("name=\"sessionId\"")) {
                encontrado = true;
                System.out.println(linea);
                String[] lineaAux = linea.split("\"");

                idSesion = lineaAux[5];

            }
            System.out.println(linea);


        }

        httpget.releaseConnection();

        return (response.getStatusLine().getStatusCode() == 200) || (response.getStatusLine().getStatusCode() == 302);


    }

    private boolean obtenerSessionPpal(String url, ArrayList<String> args, boolean mostrarRespuesta) throws Exception {


        HttpPost httpost = new HttpPost(url);

        String datosjson = "{\"session\":\"" + idSesion + "\",\"reset\":true,\"refId\":" + new Date().getTime() + ",\"version\":-1}";
        System.out.println("Json a enviar -> " + datosjson);
        httpost.setEntity(new StringEntity(datosjson, HTTP.UTF_8));


        //httpost.setHeaders(headers)
        httpost.addHeader("Content-Type", "application/json; charset=UTF-8");
        httpost.addHeader("Referer", WEB_BROWSER_URL);
        httpost.addHeader("X-Qooxdoo-Response-Type", "application/json");

        // httpost.
        HttpResponse response = httpclient.execute(httpost);


        System.out.println("Solicitud para :" + url);

        System.out.println("Cabeceras :");
        for (Header a : httpost.getAllHeaders()) {
            System.out.println(a.getValue());
        }

        //mostrarRespuesta(response, mostrarRespuesta);
        boolean encontrado = false;
        InputStreamReader isr = new InputStreamReader(response.getEntity().getContent());
        BufferedReader in = new BufferedReader(isr);
        String linea;
        while ((linea = in.readLine()) != null && !encontrado) {
            if (linea.contains("i\":")) {
                encontrado = true;
                System.out.println(linea);
                String[] lineaAux = linea.split("\"");

                idSesionPpal = lineaAux[3];

            }
            System.out.println(linea);


        }

        httpost.releaseConnection();



        return response.getStatusLine().getStatusCode() == 200;


    }

    private boolean realizarSolicitudGet(String sol, boolean mostrarRespuesta) throws Exception {

        HttpGet httpget = new HttpGet(sol);

        HttpResponse response = httpclient.execute(httpget);


        System.out.println("Solicitud para :" + sol);

        System.out.println("Cabecera :" + httpget.getAllHeaders().toString());
        for (Header a : httpget.getAllHeaders()) {
            System.out.println(a.getValue());
        }

        mostrarRespuesta(response, mostrarRespuesta);
        httpget.releaseConnection();

        return response.getStatusLine().getStatusCode() == 200;
    }

    private String realizarSolicitudPostJSON(String url, ArrayList<String> args, boolean mostrarRespuesta) throws Exception {

        HttpPost httpost = new HttpPost(url);




        /*
         * wc.Headers.Add("Content-Type: application/json; charset=UTF-8");
         * wc.Headers.Add(string.Format("Referer: {0}", new Uri(host,
         * "index.aspx"))); wc.Headers.Add("X-Qooxdoo-Response-Type:
         * application/json");
         */

        String datosjson = GsonUtility.toJson(args, idSesionPpal);
        
        
        
        httpost.setEntity(new StringEntity(datosjson, HTTP.UTF_8));


        //httpost.setHeaders(headers)
        httpost.addHeader("Content-Type", "application/json; charset=UTF-8");
        httpost.addHeader("Referer", WEB_BROWSER_URL);
        httpost.addHeader("X-Qooxdoo-Response-Type", "application/json");

        // httpost.
        HttpResponse response = httpclient.execute(httpost);

        httpost.releaseConnection();

        if (response.getStatusLine().getStatusCode() != 400) {
            InputStreamReader isr = new InputStreamReader(response.getEntity().getContent());
            BufferedReader in = new BufferedReader(isr);
            return in.readLine();
        } else {
            return null;
        }



    }

    private String realizarSolicitudPoll(String args) throws Exception {

        HttpPost httpost = new HttpPost(AJAX_ENDPOINT + "Poll");




        /*
         * wc.Headers.Add("Content-Type: application/json; charset=UTF-8");
         * wc.Headers.Add(string.Format("Referer: {0}", new Uri(host,
         * "index.aspx"))); wc.Headers.Add("X-Qooxdoo-Response-Type:
         * application/json");
         */

        String datosjson = "{\"session\":\"" + idSesionPpal + "\",\"sequenceid\":" + secuentId++ + ",\"requestid\":" + requestId++ + ",\"requests\":\""+args+"\"}";
        httpost.setEntity(new StringEntity(datosjson, HTTP.UTF_8));

        
        System.out.println("Enviamos ->" + datosjson);
        
        //httpost.setHeaders(headers)
         httpost.addHeader("Content-Type", "application/json; charset=UTF-8");
        httpost.addHeader("Referer", WEB_BROWSER_URL);
        httpost.addHeader("X-Qooxdoo-Response-Type", "application/json");
        

        // httpost.
        HttpResponse response = httpclient.execute(httpost);

       

        if (response.getStatusLine().getStatusCode() != 400) {
            InputStreamReader isr = new InputStreamReader(response.getEntity().getContent());
            BufferedReader in = new BufferedReader(isr);
            String r = in.readLine();
            System.out.println("Recibimos ->" + r);
             httpost.releaseConnection();
            return r;
        } else {
            mostrarRespuesta(response, true);
             httpost.releaseConnection();
            return null;
        }



    }

    public PlayerInfoEntity getPlayerInfo() {
        try {
            
            String RespuestajSon = realizarSolicitudPostJSON(AJAX_ENDPOINT + "GetPlayerInfo", null, true);
            PlayerInfoEntity pieRespuesta = gson.fromJson(RespuestajSon, PlayerInfoEntity.class);

            if (pieRespuesta != null) {
                return pieRespuesta;
            } else {
                return null;
            }

        } catch (Exception e) {
            System.out.println(e);
            return null;
        }



    }

    public BaseEntity getInfoBase() {
        try {
           
            ArrayList<PollEntity> pollArray ;
            String respuesta = realizarSolicitudPoll("WC:A\\fTIME:"+new Date().getTime()+"\\fCHAT:\\fWORLD:\\fGIFT:\\fACS:0\\fASS:0\\fCAT:0\\f");
           
            pollArray = GsonUtility.parsearPoll(gson, respuesta);
            
            for (PollEntity p : pollArray)
            {
                if("CITIES".equals( p.getTexto()))
                    return p.getTipo().getBases().get(0);
                   
            }
            
            return null;
           
            
            
        } catch (Exception ex) {
            System.out.println(ex);
        }
        return null;

    }

    public BaseEntity recogerTodosRecursos(ArrayList<EdificioEntity> edificios) 
    {
        
        
        
       
    }

    
}
